package com.tgy.shiroboot.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;

/***
 * @ClassName: ShiroConfig
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 20:30 2022/1/5
 * @version : V1.0
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("dwsm") DefaultWebSecurityManager dwsm){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(dwsm);
        /*
            anon:   无需认证就可以访问
            authc:  必须认证了才能访问
            user:   必须拥有“记住我”功能才能访问
            perms:  拥有对某个资源的权限才能访问
            roles:  拥有某个角色权限才能访问
         */

        //拦截
        Map<String, String> filterMap  = new LinkedHashMap<>();

        //授权，正常情况下，没有授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/upd","perms[user:upd]");
        //未授权界面
        bean.setUnauthorizedUrl("unauth");

        filterMap.put("/user/*","authc");
        bean.setLoginUrl("/toLogin");

        //设置登录的请求
        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }



    //defaultWebSecurtiyManager
    @Bean("dwsm")
    public DefaultWebSecurityManager getDefauteWebSecrityManager(@Qualifier("userRealm") UserRealm userRealm){

        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }



    //创建Realm对象 需要自定义类
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
